<template>
  <div class="login-container">
    <div class="login-box">
      <h2>智慧医疗系统登录</h2>
      <div class="login-form">
        <!-- 用户名输入框 -->
        <div class="form-item">
          <label>用户名：</label>
          <input 
            v-model="loginForm.username" 
            type="text" 
            placeholder="请输入用户名"
            @keyup.enter="handleLogin"
          />
        </div>
        
        <!-- 密码输入框 -->
        <div class="form-item">
          <label>密码：</label>
          <input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
          />
        </div>
        
        <!-- 记住密码选项 -->
        <div class="form-item remember">
          <input 
            v-model="rememberMe" 
            type="checkbox" 
            id="remember"
          />
          <label for="remember">记住密码</label>
        </div>
        
        <!-- 错误提示信息 -->
        <div v-if="loginError" class="error-message">
          {{ loginError }}
        </div>
        
        <!-- 登录按钮 -->
        <div class="form-item">
          <button 
            :disabled="loading" 
            @click="handleLogin"
            class="login-button"
          >
            {{ loading ? '登录中...' : '登录' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import api from '../utils/request';
import { useUserStore } from '../stores/user';

// 获取路由对象
const router = useRouter();
// 获取用户状态store
const userStore = useUserStore();

// 定义登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
});

// 定义状态变量
const loading = ref(false);      // 加载状态
const loginError = ref('');      // 登录错误信息
const rememberMe = ref(false);   // 记住密码

/**
 * 处理登录操作
 */
const handleLogin = async () => {
  // 表单验证
  if (!loginForm.username) {
    loginError.value = '请输入用户名';
    return;
  }
  
  if (!loginForm.password) {
    loginError.value = '请输入密码';
    return;
  }
  
  // 清空错误信息
  loginError.value = '';
  
  try {
    // 设置加载状态
    loading.value = true;
    
    // 调用后端登录接口
    const response = await api.user.login({
      usernameOrEmail: loginForm.username,
      password: loginForm.password,
      rememberMe: rememberMe.value
    });
    
    // 保存token
    localStorage.setItem('token', response.accessToken);
    
    // 如果选择记住密码
    if (rememberMe.value) {
      localStorage.setItem('username', loginForm.username);
      localStorage.setItem('remember', 'true');
    } else {
      localStorage.removeItem('username');
      localStorage.removeItem('remember');
    }
    
    // 显示登录成功消息
    ElMessage.success('登录成功！');
    
    // 延迟跳转，让用户看到成功消息
    setTimeout(() => {
      router.push('/home');
    }, 1000);
    
  } catch (error: any) {
    // 显示登录错误消息
    ElMessage.error(error.message || '登录失败，请检查用户名和密码');
    loginError.value = error.message || '登录失败，请检查用户名和密码';
  } finally {
    // 无论成功失败都关闭加载状态
    loading.value = false;
  }
};

/**
 * 生命周期钩子 - 组件挂载时执行
 * 用于检查是否有已保存的登录信息
 */
const checkSavedCredentials = () => {
  // 检查是否有记住的用户名和密码
  const savedUsername = localStorage.getItem('username');
  const remembered = localStorage.getItem('remember') === 'true';
  
  if (savedUsername && remembered) {
    loginForm.username = savedUsername;
    rememberMe.value = true;
  }
};

// 组件挂载时检查保存的凭据
checkSavedCredentials();
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-box {
  width: 500px;
  padding: 50px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 40px;
  color: #333;
  font-size: 26px;
  font-weight: 600;
}

.login-form {
  display: flex;
  flex-direction: column;
}

.form-item {
  margin-bottom: 30px;
}

.form-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-item input[type="text"],
.form-item input[type="password"] {
  width: 100%;
  padding: 15px 18px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-item input[type="text"]:focus,
.form-item input[type="password"]:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.remember {
  display: flex;
  align-items: center;
}

.remember input {
  margin-right: 5px;
}

.error-message {
  color: #ff4d4f;
  margin-bottom: 15px;
  font-size: 14px;
}

.login-button {
  width: 100%;
  padding: 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 17px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.login-button:hover {
  background-color: #40a9ff;
}

.login-button:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}
</style>
